#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>

class DictClient
{
private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop *_baseloop;
    muduo::CountDownLatch _downlatch;
    muduo::net::TcpClient _client;

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            std::cout << "连接建立" << std::endl;
            _conn = conn;
            _downlatch.countDown();
        }
        else
        {
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::string res = buf->retrieveAllAsString();
        std::cout << res << std::endl;
    }

public:
    DictClient(const std::string &ip, int port)
        : _baseloop(_loopthread.startLoop()),
          _downlatch(1),
          _client(_baseloop, muduo::net::InetAddress(ip, port), "DictClient")
    {
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&DictClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        //连接服务器
        _client.connect(); // 阻塞的
        _downlatch.wait();
    }

    bool Send(const std::string &msg)
    {
        if(_conn->connected()==false)
        {
            std::cout<<"连接已断开 发送数据失败"<<std::endl;
            return false;
        }

        _conn->send(msg);
        return true;
    }
};


int main()
{
    DictClient client("127.0.0.1",12700);
    std::string msg;
    while(1)
    {
        std::cin>>msg;
        bool ret=client.Send(msg);
        if(!ret)
            break;
    }

    return 0;

}